import Const from './const'

function Data () {
  return {
    set: set,
    get: get,
    remove: remove,
    getKey: getKey,
    setToken: setToken,
    getToken: getToken,
    setUser: setUser,
    getUser: getUser,
    clearAuthData: clearAuthData
  }

  function getKey (key) {
    return Const.DATA.KEY_PREFIX + key
  }

  function get (key) {
    if (key) {
      key = getKey(key)
      return JSON.parse(window.localStorage.getItem(key))
    }
  }

  function set (key, val) {
    if (key) {
      key = getKey(key)
      return window.localStorage.setItem(key, JSON.stringify(val))
    }
  }

  function remove (key) {
    if (key) {
      key = getKey(key)
      return window.localStorage.removeItem(key)
    }
  }

  function setToken (token) {
    let key = Const.DATA.KEY_TOKEN
    return set(key, token)
  }

  function getToken () {
    let key = Const.DATA.KEY_TOKEN
    return get(key)
  }

  function setUser (user) {
    let key = Const.DATA.KEY_USER
    return set(key, user)
  }

  function getUser () {
    let key = Const.DATA.KEY_USER
    return get(key)
  }

  function clearAuthData () {
    setToken('')
    setUser('')
  }
}

export default new Data()
